<template>
	<div class="app-container">
		<el-card>
			<template #header>
				<div class="card-header">
					<span>{{
						isEdit ? "编辑居民" : "新增居民（新增密码默认为123456）"
					}}</span>
				</div>
			</template>

			<el-form
				ref="formRef"
				:model="form"
				:rules="rules"
				label-width="100px"
				class="resident-form"
			>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="姓名" prop="name">
							<el-input v-model="form.name" placeholder="请输入居民姓名" />
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="手机号" prop="phone">
							<el-input v-model="form.phone" placeholder="请输入手机号" />
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="身份证号" prop="idCard">
							<el-input
								v-model="form.idCard"
								placeholder="请输入身份证号"
								:disabled="isEdit"
							/>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="性别" prop="gender">
							<el-radio-group v-model="form.gender">
								<el-radio label="Male">男</el-radio>
								<el-radio label="Female">女</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="出生日期" prop="birthDate">
							<el-date-picker
								v-model="form.birthDate"
								type="date"
								placeholder="选择出生日期"
								style="width: 100%"
								value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="关联房屋" prop="houseId">
							<el-select
								v-model="form.houseId"
								placeholder="请选择关联房屋"
								clearable
								style="width: 100%"
								@click.stop="loadHouses"
							>
								<el-option
									v-for="house in houseOptions"
									:key="house.id"
									:label="house.fullAddress"
									:value="house.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="24">
						<el-form-item label="居住地址" prop="address">
							<el-input
								v-model="form.address"
								type="textarea"
								:rows="2"
								placeholder="请输入详细居住地址"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item>
					<el-button type="primary" :loading="loading" @click="submitForm">
						{{ isEdit ? "保存修改" : "立即创建" }}
					</el-button>
					<el-button @click="cancel">取消</el-button>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getResident, createResident, updateResident } from "@/api/resident";
import { getHouses } from "@/api/house";

const route = useRoute();
const router = useRouter();

// 判断是否是编辑模式
const isEdit = computed(() => {
	return route.path.includes("/edit/");
});

// 表单数据
const formRef = ref(null);
const loading = ref(false);
const form = reactive({
	name: "",
	phone: "",
	idCard: "",
	gender: "Male",
	birthDate: "",
	address: "",
	houseId: null,
});

// 房屋选项
const houseOptions = ref([]);

// 表单验证规则
const rules = {
	name: [
		{ required: true, message: "请输入居民姓名", trigger: "blur" },
		{ min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
	],
	phone: [
		{ required: true, message: "请输入手机号", trigger: "blur" },
		{
			pattern: /^1[3-9]\d{9}$/,
			message: "请输入正确的手机号",
			trigger: "blur",
		},
	],
	idCard: [
		{ required: true, message: "请输入身份证号", trigger: "blur" },
		{
			pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
			message: "请输入正确的身份证号",
			trigger: "blur",
		},
	],
	gender: [{ required: true, message: "请选择性别", trigger: "change" }],
	birthDate: [{ required: true, message: "请选择出生日期", trigger: "change" }],
	address: [{ required: true, message: "请输入居住地址", trigger: "blur" }],
};

// 加载房屋选项
const loadHouses = async () => {
	try {
		const res = await getHouses({ pageSize: 100 }); // 获取所有房屋
		houseOptions.value = res.items.map((house) => ({
			id: house.id,
			fullAddress: `${house.buildingNo}栋${house.unitNo}单元${house.roomNo}室`,
		}));
	} catch (error) {
		console.error("获取房屋列表失败：", error);
	}
};

// 如果是编辑模式，加载居民信息
const loadResidentInfo = async (id) => {
	try {
		loading.value = true;
		const res = await getResident(id);
		Object.assign(form, res);
	} catch (error) {
		console.error("获取居民信息失败：", error);
		ElMessage.error("获取居民信息失败");
	} finally {
		loading.value = false;
	}
};

// 提交表单
const submitForm = () => {
	formRef.value.validate(async (valid) => {
		if (valid) {
			try {
				loading.value = true;
				if (isEdit.value) {
					await updateResident(route.params.id, form);
					ElMessage.success("修改成功");
				} else {
					await createResident(form);
					ElMessage.success("创建成功");
				}
				router.push("/resident/list");
			} catch (error) {
				console.error("保存失败：", error);
			} finally {
				loading.value = false;
			}
		}
	});
};

// 取消
const cancel = () => {
	router.back();
};

// 初始化
onMounted(() => {
	if (isEdit.value) {
		loadResidentInfo(route.params.id);
	}
	loadHouses();
});
</script>

<style lang="scss" scoped>
.app-container {
	padding: 20px;

	.resident-form {
		max-width: 1000px;
		margin: 0 auto;
		padding-top: 20px;
	}

	.card-header {
		font-size: 18px;
		font-weight: bold;
	}
}
</style>
